<?php

/*
 * Created on 2011-4-23
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

require ('../Common.inc.php');
require (SERVER_ROOT_PATH . '/config/base.config.php');
require (SERVER_ROOT_PATH . '/lib/Framework.class.php');
require (SERVER_ROOT_PATH . '/phpQuery/phpQuery/phpQuery.php');

new Framework();

$identity = urldecode($_POST['identity']);
$url = urldecode($_POST['u']);
$title = urldecode($_POST['t']);

//get the assigned url's html-----------------------------------------
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$html = curl_exec($curl);
curl_close($curl);
$reg='/<meta(\s)+http-equiv="Content-Type"(\s)+content="text\/html;(\s)+charset=(.)+"(\s)+\/{0,1}>/i';
$replacement='<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
$html=preg_replace($reg,$replacement,$html);
//---------------------------------------------------------------------


//use Preader class to get the read content----------------------------
phpQuery::$debug = false;

$html = phpQuery::newDocumentHTML($html,'utf-8');
$body = $html->find('body');

$p=new Preader2($body,$html->find('title:first')->html());

$content=$p->getHtml();
$replace=array("'"=>'&apos;');
$content=strtr($content,$replace);
//---------------------------------------------------------------------


//save to db------------------------------------------------------------
$u=new User('w');
//title进行一次unhtml是因为title要当字符串显示，而content要当页面内容的一部分，所以不用
$rs=$u->insertRecord(urldecode($identity),String::unHtml($title),$content,$url);
//-----------------------------------------------------------------------

if($rs){
	$html=<<<__SUCCESS
	<body>
		<p>收藏成功!</p>
		网页会自动跳转回原来页面。如果未能跳转，请<a href="$url">点击此处.</a>
	</body>
	<script type="text/javascript">
		setTimeout(function(){
			window.location.href=$url;
		},3000);
	</script>
__SUCCESS;
}else{
	$html=<<<__ERROR
		<body>
			<p>添加失败!</p>
			<a href="$url" >回到原网页</a>
		</body>
__ERROR;
}

echo $html;
?>
